﻿// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone

using BlazorAdmin.Models;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;

namespace BlazorAdmin.Web.Shared.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public static class TreeItemExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="navigations"></param>
        /// <param name="selectedItems"></param>
        /// <param name="render"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public static List<TreeViewItem<Navigation>> ToTreeItemList(this IEnumerable<Navigation> navigations, List<string> selectedItems, RenderFragment<Navigation> render, int parentId = 0)
        {
            var trees = new List<TreeViewItem<Navigation>>();
            var roots = navigations.Where(i => i.ParentID == parentId).OrderBy(i => i.Application).ThenBy(i => i.SortNo);
            foreach (var node in roots)
            {
                TreeViewItem<Navigation> treeItem = new(node)
                {
                    Text = node.Name,
                    Icon = node.Icon,
                    CheckedState = selectedItems.Any(v => node.ID.ToString() == v) ? CheckboxState.Checked : CheckboxState.UnChecked,
                    Template = render,
                    Items = ToTreeItemList(navigations, selectedItems, render, node.ID)
                };
                trees.Add(treeItem);
            }
            return trees;
        }
    }
}